﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChgDoc.Entity;

namespace ChgDoc.Edit
{
	public partial class Admin : System.Web.UI.MasterPage
	{
        private object[] _attributes;

        public Admin()
        {
            this.Init += new EventHandler( Admin_Init );
        }

        void Admin_Init( object sender, EventArgs e )
        {
            _attributes = (Page.GetType().GetCustomAttributes( typeof( AdminPageAttribute ), true ));
            if (!_attributes.Any())
                throw new Exception( string.Format( "Page {0} does not define any AdminPageAttributes", Page.GetType().Name ) );

            AdminPageAttribute pageAttributes = (AdminPageAttribute)_attributes[0];

            if (!Visitor.HasPermission( pageAttributes.PermissionCode ))
                Response.Redirect( "loginpage.aspx", true );                
        }

		protected void Page_Load( object sender, EventArgs e )
		{
            AdminPageAttribute pageAttributes = (AdminPageAttribute)_attributes[0];
			SetTitle( pageAttributes.Title );

            if (Visitor.IsAnonymous)
            {
                litUser.Text = "<a href=\"loginpage.aspx\">Login</a>";
                menugroup.Visible = false;
            }
            else
            {
                litUser.Text = "<span>" + Visitor.DisplayName + "</span> | <a href=\"loginpage.aspx?act=lo\">Logout</a>";
                menugroup.Visible = true;
            }


            string disableSetupModeMenu = Config.Current.DisableSetup ? " $(document).ready( function() { $('.setupMode').hide(); });" : "";
            litScript.Text = "<script type='text/javascript'>var appGlobal = { serverUrl : '" + Config.BaseUrl + "'}; " + disableSetupModeMenu + "</script>";
		}
        
		public void SetTitle( string title )
		{
			litTitle.Text = title;
			litPageTitle.Text = title;
		}

		public enum MessageLevel { Info, Error }
		
		public void ClearMessage()
		{
			litMessage.Text = string.Empty;
		}

		public void SetMessage(MessageLevel level, string text)
		{
			if (string.IsNullOrEmpty( text ))
				return;

			text = StringMagic( text );

			SetMessage( new List<Tuple<MessageLevel, string>> { new Tuple<MessageLevel, string>( level, text )} );
		}

        // TODO: Replace with FromMagicString
		private string StringMagic(string text)
		{
			// Find {...} in text
			int openIndex = text.IndexOf( '{' );
			if (openIndex == -1)
				return text;

			int closeIndex = text.IndexOf( '}' );
			if (closeIndex == -1)
				return text;
			
			if (openIndex > closeIndex)
				return text;

			// if text has " {{ " then don't process.
			if (text[openIndex + 1] == '{')
				return text;

			string[] parts = text.Substring( openIndex + 1, closeIndex - openIndex - 1 ).Split( ':' );

			if (parts.Length != 2)
				return text;

			string replace;
			switch (parts[0].ToLower())
			{
				case "qs":
					replace = Request.QueryString[ parts[ 1 ] ];
					break;
			
				default:
					return text;
			}

			// recurse to resolve any other {...} fields
			return StringMagic( text.Substring( 0, openIndex ) + replace + text.Substring( closeIndex + 1 ) );
		}

		public void SetMessage( IEnumerable<Tuple<MessageLevel, string>> messages )
		{
			if (!messages.Any())
				return;

			StringBuilder msgbox = new StringBuilder();
			msgbox.Append( "<div class=\"messageBox\">" );
			
			foreach (var message in messages)
				msgbox.AppendFormat( "<div class=\"{0}\"><img src=\"{1}edit/content/img/icon/{2}.png\"/><span>{3}</span></div>", message.Item1, Config.BaseUrl, message.Item1, message.Item2 );

			msgbox.Append( "</div>" );

			litMessage.Text = msgbox.ToString();
		}

        
	}
}